package com.video.dao.http;

import com.video.model.Transcript;
import com.video.utils.constant.UrlConstant;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class DeepSeekRecognitionService {

    public List<Transcript> recognize(String audioFilePath) throws IOException {
        OkHttpClient client = new OkHttpClient();
        File audioFile = new File(audioFilePath);
        // 将音频文件编码为 Base64
        byte[] fileContent = Files.readAllBytes(audioFile.toPath());
        String encodedFile = Base64.getEncoder().encodeToString(fileContent);

        // 创建 JSON 请求体
        JsonObject jsonBody = new JsonObject();
        jsonBody.addProperty("file", encodedFile);
        jsonBody.addProperty("format", "wav");

        RequestBody requestBody = RequestBody.create(
                jsonBody.toString(),
                MediaType.parse("application/json")
        );

        // 创建请求
        Request request = new Request.Builder()
                .url(UrlConstant.DEEP_SEEK_AUDIO_API_URL)
                .addHeader("Authorization", "Bearer " + UrlConstant.DEEP_SEEK_API_KEY)
                .post(requestBody)
                .build();

        // 打印请求信息
        System.out.println("Request URL: " + request.url());
        System.out.println("Request Headers: " + request.headers());
        System.out.println("Request Body: " + jsonBody);

        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            // 打印响应信息
            System.out.println("Response Code: " + response.code());
            System.out.println("Response Headers: " + response.headers());

            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 解析响应
            String text = response.body().string();
            System.out.println(text);
        }
        return null;
    }

    private List<Transcript> parseResponse(String responseBody) {
        List<Transcript> transcripts = new ArrayList<>();
        JsonObject jsonResponse = JsonParser.parseString(responseBody).getAsJsonObject();
        JsonArray segments = jsonResponse.getAsJsonArray("segments");

        for (int i = 0; i < segments.size(); i++) {
            JsonObject segment = segments.get(i).getAsJsonObject();
            String text = segment.get("text").getAsString();
            long startTime = segment.get("start").getAsLong();
            long endTime = segment.get("end").getAsLong();
            transcripts.add(new Transcript(text, startTime, endTime));
        }

        return transcripts;
    }
}
